//
//  SCMapViewController.m
//  Shuaiche
//
//  Created by 党帅 on 2020/6/28.
//  Copyright © 2020 ShuaiChe. All rights reserved.
//

#import "SCMapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface SCMapViewController ()<MKMapViewDelegate,UITableViewDataSource,UITextFieldDelegate,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (strong, nonatomic) IBOutlet UITextField *searchTextField;
@property (weak, nonatomic) IBOutlet UIButton *cancelSearchButton;

@property (weak, nonatomic) IBOutlet UITableView *searchResultTable;
@property (weak, nonatomic) IBOutlet UIView *mapContaninerView;

@property (nonatomic, assign) MKCoordinateSpan coordinateSpan;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKLocalSearchRequest *localSearchRequest;

@property (nonatomic, strong) NSMutableArray *localSearchResult;

@property (nonatomic, assign) BOOL hasCenterLocation;
@property (nonatomic, assign) BOOL isSearchingKeyword;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableTop;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableBottom;
@property (nonatomic, strong) CLPlacemark *currentPlace;
@property (nonatomic, assign) CLLocationCoordinate2D currentCoordinate;
@end

@implementation SCMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"定位";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
  
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(selectCurrentLocation)];
  
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
    [barItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    
    self.navigationItem.rightBarButtonItem = barItem;
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    [_locationManager requestWhenInUseAuthorization];
    _localSearchRequest = [[MKLocalSearchRequest alloc] init];
    _searchResultTable.dataSource = self;
    _searchResultTable.delegate = self;
    _mapView.delegate = self;
    _coordinateSpan = MKCoordinateSpanMake(0.021321, 0.019366);
    if (_lat && _lon) {
        _currentCoordinate = CLLocationCoordinate2DMake(_lat.doubleValue, _lon.doubleValue);
    } else {
        _currentCoordinate = _mapView.userLocation.coordinate;
    }
    _mapView.userTrackingMode = MKUserTrackingModeFollow;
    _mapView.mapType = MKMapTypeStandard;
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    _mapView.showsUserLocation = YES;
    
    MKCoordinateRegion region = MKCoordinateRegionMake(_currentCoordinate, _coordinateSpan);
    [_mapView setRegion:region animated:YES];
    _searchTextField.delegate = self;
    _tableTop.constant = kSCScreenWidth + 5;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHeightChanged:) name:UIKeyboardDidChangeFrameNotification object:nil];
}

- (void)selectCurrentLocation {
    CLLocationCoordinate2D center = _mapView.centerCoordinate;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:center.latitude longitude:center.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count) {
            CLPlacemark *mark = placemarks.firstObject;
            if (self.didSelectAddress) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                NSString *name = mark.name ? mark.name : @"";
                dic[kProvinceName] = mark.administrativeArea;
                dic[kCityName] = mark.locality;
                dic[kDistrictName] = mark.subLocality;
                dic[kAddress] = [NSString stringWithFormat:@"%@ %@",mark.thoroughfare,name] ;
                dic[@"lat"] = @(mark.location.coordinate.latitude);
                dic[@"lon"] = @(mark.location.coordinate.longitude);
                self.didSelectAddress(dic);
            }
        }
    }];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    if (_isSearchingKeyword) {
        return;
    }
    //获取当前位置
    if (!_hasCenterLocation) {
        _hasCenterLocation = YES;
//        CLLocationCoordinate2D center = userLocation.location.coordinate;
        
        
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (!error && placemarks.count) {
                    _currentPlace = placemarks.firstObject;
            }
            [self startLocalSearch:@"车" toCenter:_currentCoordinate];
        }];
    }
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    if (_isSearchingKeyword) {
        return;
    }
    
    if (_hasCenterLocation) {
        CLLocationCoordinate2D center = mapView.centerCoordinate;
        [self startLocalSearch:@"车" toCenter:center];
    }
}

- (void)startLocalSearch:(NSString *)keyword toCenter:(CLLocationCoordinate2D)center {
    _localSearchRequest.naturalLanguageQuery = keyword;
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(center, 200, 200);
   _localSearchRequest.region = region;
   MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:_localSearchRequest];
   [search startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
       [self.localSearchResult removeAllObjects];
       if (!_isSearchingKeyword && _currentPlace) {
           [self.localSearchResult addObject:_currentPlace];
       }
       [self.localSearchResult addObjectsFromArray:response.mapItems];
       [self.searchResultTable reloadData];
   }];
}

- (IBAction)moveMapToCenter:(UIButton *)sender {
    MKUserLocation *userLocation = _mapView.userLocation;
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
}

- (void)mapViewMemoryRelease:(MKMapView *)mapView {
    if (mapView.region.span.longitudeDelta < 0.005 || mapView.region.span.latitudeDelta < 0.005) {
        return;
    }
    
    float longitudeDelta = mapView.region.span.longitudeDelta - _coordinateSpan.longitudeDelta;
    float latitudeDelta = mapView.region.span.latitudeDelta - _coordinateSpan.latitudeDelta;
    
    if ( fabs(longitudeDelta) < 0.00005 && fabs(latitudeDelta) <0.00005) {
        return;
    }
    MKMapType type  = mapView.mapType;
    mapView.mapType = type == MKMapTypeStandard ? MKMapTypeHybrid : MKMapTypeStandard;
    mapView.mapType = type;
    _coordinateSpan = mapView.region.span;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _localSearchResult.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *resue = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:resue];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:resue];
        cell.textLabel.font = SC_FONT(14);
        cell.textLabel.textColor = SC_TextBlack_Primary;
    }
    id item = _localSearchResult[indexPath.row];
    if ([item isKindOfClass:MKMapItem.class]) {
        MKMapItem *mapitem = (MKMapItem *)item;
        cell.textLabel.text = mapitem.name;
        cell.imageView.image = [UIImage imageNamed:@"location_icon"];
    } else if ([item isKindOfClass:CLPlacemark.class]) {
        CLPlacemark *mark = (CLPlacemark *)item;
        cell.textLabel.text = mark.name;
        cell.imageView.image = [UIImage imageNamed:@"location_self"];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CLPlacemark *mark = nil;
    id item = _localSearchResult[indexPath.row];
    if ([item isKindOfClass:MKMapItem.class]) {
        MKMapItem *mapitem = (MKMapItem *)item;
        mark = mapitem.placemark;
    } else if ([item isKindOfClass:CLPlacemark.class]) {
        mark = item;
    }
    if (self.didSelectAddress) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[kProvinceName] = mark.administrativeArea;
        dic[kCityName] = mark.locality;
        dic[kDistrictName] = mark.subLocality;
        dic[kAddress] = mark.thoroughfare;
        dic[@"lat"] = @(mark.location.coordinate.latitude);
        dic[@"lon"] = @(mark.location.coordinate.longitude);
        self.didSelectAddress(dic);
    }
    NSLog(@">>>>%@",mark.name);
}

- (NSMutableArray *)localSearchResult {
    if (!_localSearchResult) {
        _localSearchResult = [NSMutableArray arrayWithCapacity:0];
    }
    return _localSearchResult;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self beginSearchKeyword];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self endSearchKeyword];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length) {
        [self startLocalSearch:textField.text toCenter:_mapView.centerCoordinate];
    }
    return YES;
}

- (void)beginSearchKeyword {
    _isSearchingKeyword = YES;
    _cancelSearchButton.hidden = NO;
    _tableTop.constant = 5;
    [_localSearchResult removeAllObjects];
    [_searchResultTable reloadData];
}

- (void)endSearchKeyword {
    _tableTop.constant = kSCScreenWidth + 5;
    _cancelSearchButton.hidden = YES;
    _searchTextField.text = nil;
}

- (void)keyboardHeightChanged:(NSNotification *)noti {
    if (![noti.name isEqualToString:UIKeyboardDidChangeFrameNotification]) return;
    NSDictionary *info = noti.userInfo;
    if (!info) return;
    NSValue *afterValue = info[UIKeyboardFrameEndUserInfoKey];
    CGRect after = afterValue.CGRectValue;
    CGFloat y = CGRectGetMinY(after);
    _tableBottom.constant = y == kSCScreenHeight ? 0 : y;
    
//    if (after.size.width <= 0 && after.size.height <= 0) return;
}

- (IBAction)cancelSearchButtonClick:(UIButton *)sender {
    [_searchTextField endEditing:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
